<template>
  <div class="space-container">
    <!-- 查询条件卡片 -->
    <el-card class="search-card">
      <template #header>
        <div class="card-header">
          <span>广告位查询</span>
        </div>
      </template>
      
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="媒体">
          <el-select v-model="searchForm.mediaId" placeholder="请选择媒体" clearable filterable>
            <el-option
              v-for="media in mediaOptions"
              :key="media.id"
              :label="media.name"
              :value="media.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="广告位">
          <el-input v-model="searchForm.name" placeholder="请输入广告位名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格卡片 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>广告位列表</span>
        </div>
      </template>

          <!-- 广告位列表表格 -->
          <el-table
            :data="spaceList"
            style="width: 100%"
            v-loading="loading"
            stripe
          >
            <el-table-column prop="id" label="ID" width="160" />
            <el-table-column prop="name" label="广告位" width="200" />
            <el-table-column label="媒体" width="260">
              <template #default="{ row }">
                {{ getMediaNameById(row.mediaId) }} ({{ row.mediaId }})
              </template>
            </el-table-column>
            <el-table-column prop="adFormat" label="广告位类型" width="100">
              <template #default="{ row }">
                {{ getSpaceTypeName(row.adFormat) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                  {{ row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="bbj" label="保价开关" width="100">
              <template #default="{ row }">
                {{ row.bbj == 1 ? '开启' : '关闭' }}
              </template>
            </el-table-column>
            <el-table-column prop="bbjFloor" label="底价" width="100">
              <template #default="{ row }">
                {{ row.bbjFloor }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            
            <el-table-column label="操作" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                <el-button type="success" size="small" @click="handleReport(row)">日报</el-button>
                <el-button type="warn" size="small" @click="handleHourReport(row)">时报</el-button>
                <el-button type="danger" size="small" @click="handleLog(row)">日志</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :total="pagination.total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :hide-on-single-page="false"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>

      <!-- 日志弹窗 -->
      <el-dialog
        v-model="logDialogVisible"
        title="操作日志"
        width="80%"
        :before-close="handleLogDialogClose"
      >
        <el-table
          :data="logList"
          v-loading="logLoading"
          stripe
          style="width: 100%; margin-bottom: 20px;"
          max-height="400"
        >
          <el-table-column label="序号" width="80">
            <template #default="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="IP地址" width="300">
            <template #default="{ row }">
              {{ row.url }}
            </template>
          </el-table-column>
          <el-table-column label="日志开关" width="200">
            <template #default="{ row }">
              <el-switch
                v-model="row.logEnable"
                active-text="开"
                inactive-text="关"
                @change="handleLogSwitchChange(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="有无广告" width="200">
            <template #default="{ row }">
              <el-switch
                v-model="row.logSuccess"
                active-text="有广告"
                inactive-text="无广告"
                @change="handleLogSwitchChange(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="日志数量" width="200">
            <template #default="{ row }">
              <el-input-number
                v-model="row.logCount"
                :min="1"
                :max="1000"
                size="small"
                controls-position="right"
                @change="handleLogCountChange(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="发送">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="handleSendLog(row)"
              >
                发送
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 日志列表显示 -->
        <h3>最近10条记录 {{ currentSpaceId }}</h3>
        <el-button @click="handleQueryLast10Records">查询日志</el-button>
        <el-table
          :data="last10Records"
          v-loading="last10RecordsLoading"
          stripe
          style="width: 100%"
          max-height="400"
          class="last10-records-table"
        >
          <el-table-column prop="adspaceId" label="广告位ID" width="160" />
          <el-table-column prop="request" label="请求参数" min-width="200">
            <template #default="{ row }">
              <el-tooltip :content="row.request" placement="top" :disabled="!row.request">
                <div class="text-ellipsis">{{ row.request || '-' }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="response" label="响应参数" min-width="200">
            <template #default="{ row }">
              <el-tooltip :content="row.response" placement="top" :disabled="!row.response">
                <div class="text-ellipsis">{{ row.response || '-' }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="insertTime" label="插入时间" width="160" />
        </el-table>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleLogDialogClose">关闭</el-button>
          </span>
        </template>
      </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { fetchSpaceData, type ApiSpaceItem, fetchLogData, type LogResponse, type LogPageParams, pushLogRecord, fetchLast10Records, type Last10RecordItem } from '@/api/space'
import { fetchMediaData, type ApiMediaItem } from '@/api/media'

interface SpaceItem {
  id: string
  name: string
  mediaId: string
  mediaName: string
  type: number
  status: number
  width: number
  height: number
  floorPrice: number
  createTime: string
  updateTime: string
}

interface SearchForm {
  name: string
  mediaId: string
}

interface MediaOption {
  id: string
  name: string
}

const router = useRouter()
const loading = ref(false)
const spaceList = ref<SpaceItem[]>([])
const mediaOptions = ref<MediaOption[]>([])

const searchForm = reactive<SearchForm>({
  name: '',
  mediaId: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取广告位类型标签
const getTypeTagType = (type: number) => {
  const typeMap: Record<number, string> = {
    1: 'primary',
    2: 'success', 
    3: 'warning',
    4: 'info'
  }
  return typeMap[type] || 'default'
}

// 获取广告位类型标签文本
const getTypeLabel = (type: number) => {
  const labelMap: Record<number, string> = {
    1: '横幅广告',
    2: '插屏广告',
    3: '视频广告',
    4: '原生广告'
  }
  return labelMap[type] || '未知类型'
}

// 加载媒体选项数据
const loadMediaOptions = async () => {
  try {
    const params = {
      current: 1,
      size: 1000 // 获取所有媒体数据
    }
    
    const response = await fetchMediaData(params)
    mediaOptions.value = response.records.map(item => ({
      id: item.id,
      name: item.name
    }))
  } catch (error) {
    console.error('加载媒体选项失败:', error)
    ElMessage.error('加载媒体选项失败')
  }
}

// 加载广告位数据
const loadSpaceData = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.currentPage,
      size: pagination.pageSize,
      name: searchForm.name || undefined,
      mediaId: searchForm.mediaId || undefined
    }
    
    const response = await fetchSpaceData(params)
    spaceList.value = response.records
    pagination.total = response.totalRow
  } catch (error) {
    console.error('加载广告位数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  loadSpaceData()
}

// 根据媒体ID获取媒体名称
const getMediaNameById = (mediaId: string) => {
  const media = mediaOptions.value.find(item => item.id === mediaId)
  return media ? media.name : mediaId
}

// 根据广告位类型获取中文名称
const getSpaceTypeName = (type: number) => {
  const typeMap: { [key: number]: string } = {
    "1": '横幅',
    "2": '插屏',
    "3": '全屏',
    "4": '视频',
    "5": '原生',
    "6": '激励视频',
    "7": 'HTML',
    "8": '小程序'
  }
  return typeMap[type] || `未知(${type})`
}

// 重置搜索条件
const handleReset = () => {
  searchForm.name = ''
  searchForm.mediaId = ''
  pagination.currentPage = 1
  loadSpaceData()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadSpaceData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  loadSpaceData()
}

// 编辑广告位
const handleEdit = (row: SpaceItem) => {
  ElMessage.info(`编辑广告位: ${row.name}`)
  // 这里可以跳转到编辑页面或打开编辑对话框
}

// 查看日报
const handleReport = (row: SpaceItem) => {
  router.push({
    path: '/report/spaceDay',
    query: { adspaceId: row.id }
  })
}

// 查看时报
const handleHourReport = (row: SpaceItem) => {
  router.push({
    path: '/report/spaceHour',
    query: { adspaceId: row.id }
  })
}

// 日志弹窗相关状态
const logDialogVisible = ref(false)
const logLoading = ref(false)
const logList = ref<string[]>([])
const currentSpaceId = ref('')

const logPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 最近10条记录相关状态
const last10Records = ref<Last10RecordItem[]>([])
const last10RecordsLoading = ref(false)

// 查看日志
const handleLog = (row: SpaceItem) => {
  currentSpaceId.value = row.id
  logDialogVisible.value = true
  loadLogData()
}

// 加载日志数据
const loadLogData = async () => {
  logLoading.value = true
  try {
    
    const response = await fetchLogData()
    logList.value = response.map(item => ({
      url: item,
      logEnable: false,
      logCount: 1,
      logSuccess: false
    }))
  } catch (error) {
    console.error('加载日志数据失败:', error)
    ElMessage.error('加载日志数据失败')
  } finally {
    logLoading.value = false
  }
}

// 获取日志类型标签
const getLogTypeTag = (type: number) => {
  const typeMap: Record<number, string> = {
    1: 'success', // 创建
    2: 'primary', // 修改
    3: 'warning', // 删除
    4: 'info'     // 其他
  }
  return typeMap[type] || 'default'
}

// 日志开关变化处理
const handleLogSwitchChange = (row: SpaceItem) => {
  // 这里可以添加实际的API调用来更新服务器状态
  console.log('日志开关状态:', row.logEnable, '广告位ID:', currentSpaceId.value)
}

// 日志数量变化处理
const handleLogCountChange = (row: SpaceItem) => {
  // 这里可以添加实际的API调用来更新服务器状态
  console.log('日志数量:', row.logCount, '广告位ID:', currentSpaceId.value)
}

// 发送日志处理
const handleSendLog = (row: SpaceItem) => {
  ElMessageBox.confirm(
    `确定要发送广告位 "${currentSpaceId.value}" 的日志吗？\n日志数量: ${row.logCount || 1}`,
    '发送日志确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      // 调用实际的API接口
      const result = await pushLogRecord({
        url: row.url,
        adSpaceId: currentSpaceId.value,
        logCount: row.logCount || 1,
        logEnable: row.logEnable || false,
        logSuccess: row.logSuccess || false
      })
      
      if (result.success) {
        ElMessage.success(`广告位 ${currentSpaceId.value} 的日志发送成功！`)
      } else {
        ElMessage.error(result.message || '发送日志失败')
      }
    } catch (error) {
      console.error('发送日志失败:', error)
      ElMessage.error('发送日志失败，请稍后重试')
    }
  }).catch(() => {
    ElMessage.info('已取消发送日志')
  })
}

// 获取日志类型名称
const getLogTypeName = (type: number) => {
  const nameMap: Record<number, string> = {
    1: '创建',
    2: '修改',
    3: '删除',
    4: '其他'
  }
  return nameMap[type] || '未知'
}

// 查询最近10条记录
const handleQueryLast10Records = async () => {
  try {
    const response = await fetchLast10Records(currentSpaceId.value)
    last10Records.value = response
  } catch (error) {
    console.error('获取最近10条记录失败:', error)
    ElMessage.error('获取最近10条记录失败')
  }
}

// 日志弹窗关闭处理
const handleLogDialogClose = () => {
  logDialogVisible.value = false
  logList.value = []
  logPagination.currentPage = 1
  logPagination.total = 0
  last10Records.value = []
}

// 日志分页大小改变
const handleLogSizeChange = (size: number) => {
  logPagination.pageSize = size
  logPagination.currentPage = 1
  loadLogData()
}

// 日志当前页改变
const handleLogCurrentChange = (page: number) => {
  logPagination.currentPage = page
  loadLogData()
}

onMounted(async () => {
  await loadMediaOptions()
  await loadSpaceData()
})
</script>

<style scoped>
.space-container {
  padding: 20px;
  min-height: calc(100vh - 60px); /* 减去顶部导航栏高度 */
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.search-card {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.table-card {
  margin-top: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.log-pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 日志弹窗样式 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-table) {
  margin-bottom: 20px;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
}

/* 日志表格样式 */
:deep(.log-table .el-table__body-wrapper) {
  max-height: 400px;
  overflow-y: auto;
}

/* 卡片标题样式 */
.card-header {
  font-weight: 600;
  color: #2c3e50;
  font-size: 16px;
}

/* 最近10条记录样式 */
.last10-records-section {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.last10-records-section h3 {
  margin: 0 0 15px 0;
  color: #495057;
  font-size: 16px;
  font-weight: 600;
}

.last10-records-table {
  background-color: #ffffff;
  border-radius: 4px;
  overflow: hidden;
}

.text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

/* 操作类型标签样式 */
:deep(.el-tag) {
  font-size: 12px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  :deep(.el-dialog) {
    width: 90% !important;
  }
}

/* 按钮样式 */
.el-button {
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.el-button--primary:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

/* 表单元素样式 */
:deep(.el-input__wrapper),
:deep(.el-select__wrapper),
:deep(.el-input-number__wrapper) {
  border-radius: 8px;
  border: 1px solid rgba(102, 126, 234, 0.2);
  background: rgba(255, 255, 255, 0.9);
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover),
:deep(.el-select__wrapper:hover),
:deep(.el-input-number__wrapper:hover) {
  border-color: rgba(102, 126, 234, 0.4);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
}

:deep(.el-input__wrapper.is-focus),
:deep(.el-select__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
  transform: translateY(-1px);
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

:deep(.el-table__header-wrapper) {
  border-radius: 12px 12px 0 0;
  overflow: hidden;
}

:deep(.el-table th) {
  font-weight: 600;
  border: none;
}

:deep(.el-table th.el-table__cell) {
  background-color: transparent;
}

/* 分页样式 */
.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.log-pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-pagination .el-pager li) {
  color: #2c3e50;
  font-weight: 500;
}

:deep(.el-pagination .el-pager li.active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
  border-radius: 4px;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

.space-container {
  animation: fadeIn 0.6s ease-out;
}

.search-card {
  animation: slideInUp 0.6s ease-out;
}

.table-card {
  animation: slideInUp 0.8s ease-out;
}
</style>